// 订单处理功能实现

DOM.on(window, 'load', () => {
  let currentPage = 1;
  const pageSize = 10;
  
  // 渲染订单表格
  function renderOrders(filters = {}) {
    const ordersTable = DOM.$('#orders-table tbody');
    ordersTable.innerHTML = '';
    
    const ordersData = dataManager.getOrders(filters, currentPage, pageSize);
    
    if (ordersData.orders.length === 0) {
      const emptyRow = DOM.create('tr');
      emptyRow.innerHTML = `
        <td colspan="7" style="text-align: center; padding: 40px; color: #999;">
          暂无订单数据
        </td>
      `;
      ordersTable.appendChild(emptyRow);
      return;
    }
    
    ordersData.orders.forEach(order => {
      const row = DOM.create('tr');
      row.setAttribute('data-order-id', order.id);
      
      // 格式化日期
      const date = new Date(order.createdAt).toLocaleString('zh-CN');
      
      // 获取状态标签和样式
      const statusLabel = orderStatusMachine.getStateLabel(order.status);
      let badgeClass = '';
      switch (order.status) {
        case 'PENDING': badgeClass = 'badge-warning'; break;
        case 'PAID': badgeClass = 'badge-primary'; break;
        case 'SHIPPED': badgeClass = 'badge-info'; break;
        case 'DELIVERED': badgeClass = 'badge-success'; break;
        case 'COMPLETED': badgeClass = 'badge-success'; break;
        case 'CANCELLED': badgeClass = 'badge-secondary'; break;
        case 'REFUNDED': badgeClass = 'badge-danger'; break;
        case 'RETURNED': badgeClass = 'badge-danger'; break;
        default: badgeClass = 'badge-secondary';
      }
      
      // 构建订单商品信息显示
      let productInfo = '';
      if (order.products.length > 1) {
        productInfo = `${order.products[0].productName} 等${order.products.length}件`;
      } else {
        productInfo = order.products[0].productName;
      }
      
      // 构建操作按钮
      const actionButtons = buildOrderActionButtons(order);
      
      row.innerHTML = `
        <td>${order.id}</td>
        <td>${order.customer.name}</td>
        <td>${productInfo}</td>
        <td>¥${order.totalAmount.toFixed(2)}</td>
        <td><span class="badge ${badgeClass}">${statusLabel}</span></td>
        <td>${date}</td>
        <td>${actionButtons}</td>
      `;
      
      ordersTable.appendChild(row);
    });
    
    // 绑定操作按钮事件
    bindOrderActions();
    
    // 渲染分页
    renderPagination(ordersData.totalPages, currentPage);
  }
  
  // 根据订单状态构建操作按钮
  function buildOrderActionButtons(order) {
    let buttons = '';
    
    // 查看详情按钮（所有状态都有）
    buttons += `<button class="btn btn-secondary" style="padding: 4px 12px; font-size: 12px; margin-right: 5px;" data-order-id="${order.id}" data-action="view">查看</button>`;
    
    // 根据状态添加相应的操作按钮
    switch (order.status) {
      case 'PENDING':
        buttons += `<button class="btn btn-danger" style="padding: 4px 12px; font-size: 12px; margin-right: 5px;" data-order-id="${order.id}" data-action="cancel">取消</button>`;
        buttons += `<button class="btn btn-primary" style="padding: 4px 12px; font-size: 12px;" data-order-id="${order.id}" data-action="pay">确认支付</button>`;
        break;
      case 'PAID':
        buttons += `<button class="btn btn-primary" style="padding: 4px 12px; font-size: 12px;" data-order-id="${order.id}" data-action="ship">发货</button>`;
        break;
      case 'SHIPPED':
        buttons += `<button class="btn btn-success" style="padding: 4px 12px; font-size: 12px;" data-order-id="${order.id}" data-action="deliver">确认送达</button>`;
        break;
      case 'DELIVERED':
        buttons += `<button class="btn btn-success" style="padding: 4px 12px; font-size: 12px;" data-order-id="${order.id}" data-action="complete">完成订单</button>`;
        break;
    }
    
    return buttons;
  }
  
  // 绑定订单操作按钮事件
  function bindOrderActions() {
    DOM.$$('#orders-table [data-action]').forEach(btn => {
      DOM.on(btn, 'click', () => {
        const orderId = btn.getAttribute('data-order-id');
        const action = btn.getAttribute('data-action');
        
        switch (action) {
          case 'view':
            viewOrderDetail(orderId);
            break;
          case 'cancel':
            updateOrderStatus(orderId, 'CANCELLED', '确定要取消该订单吗？');
            break;
          case 'pay':
            updateOrderStatus(orderId, 'PAID', '确认该订单已支付？');
            break;
          case 'ship':
            updateOrderStatus(orderId, 'SHIPPED', '确认发货？');
            break;
          case 'deliver':
            updateOrderStatus(orderId, 'DELIVERED', '确认该订单已送达？');
            break;
          case 'complete':
            updateOrderStatus(orderId, 'COMPLETED', '确认完成该订单？');
            break;
        }
      });
    });
  }
  
  // 查看订单详情
  function viewOrderDetail(orderId) {
    const order = dataManager.data.orders.find(o => o.id === orderId);
    if (order) {
      let details = `订单详情\n\n`;
      details += `订单号: ${order.id}\n`;
      details += `客户: ${order.customer.name}\n`;
      details += `客户电话: ${order.customer.phone}\n`;
      details += `订单金额: ¥${order.totalAmount.toFixed(2)}\n`;
      details += `订单状态: ${orderStatusMachine.getStateLabel(order.status)}\n`;
      details += `创建时间: ${new Date(order.createdAt).toLocaleString('zh-CN')}\n`;
      details += `更新时间: ${new Date(order.updatedAt).toLocaleString('zh-CN')}\n\n`;
      details += `商品清单:\n`;
      
      order.products.forEach((item, index) => {
        const variantInfo = item.variant.attributes 
          ? Object.entries(item.variant.attributes)
              .map(([key, value]) => `${key}: ${value}`)
              .join(', ')
          : '';
        details += `${index + 1}. ${item.productName} ${variantInfo} x ${item.quantity} = ¥${item.subtotal.toFixed(2)}\n`;
      });
      
      alert(details);
    }
  }
  
  // 更新订单状态
  function updateOrderStatus(orderId, newStatus, confirmMessage) {
    if (confirm(confirmMessage)) {
      const success = dataManager.updateOrderStatus(orderId, newStatus);
      if (success) {
        alert('订单状态更新成功！');
        renderOrders();
      } else {
        alert('订单状态更新失败，可能是状态转换不允许。');
      }
    }
  }
  
  // 渲染分页控件
  function renderPagination(totalPages, current) {
    // 移除旧的分页控件
    const oldPagination = DOM.$('#orders-table + .pagination');
    if (oldPagination) {
      oldPagination.remove();
    }
    
    // 创建新的分页控件
    const tableContainer = DOM.$('#orders-table').parentElement;
    const pagination = DOM.create('div', 'pagination');
    
    // 上一页
    const prevBtn = DOM.create('button');
    prevBtn.innerHTML = '‹';
    prevBtn.disabled = current === 1;
    DOM.on(prevBtn, 'click', () => {
      if (current > 1) {
        currentPage--;
        renderOrders();
      }
    });
    pagination.appendChild(prevBtn);
    
    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
      const pageBtn = DOM.create('button');
      pageBtn.textContent = i;
      if (i === current) {
        pageBtn.classList.add('active');
      }
      DOM.on(pageBtn, 'click', () => {
        currentPage = i;
        renderOrders();
      });
      pagination.appendChild(pageBtn);
    }
    
    // 下一页
    const nextBtn = DOM.create('button');
    nextBtn.innerHTML = '›';
    nextBtn.disabled = current === totalPages;
    DOM.on(nextBtn, 'click', () => {
      if (current < totalPages) {
        currentPage++;
        renderOrders();
      }
    });
    pagination.appendChild(nextBtn);
    
    tableContainer.appendChild(pagination);
  }
  
  // 导出订单数据
  function exportOrders() {
    const orders = dataManager.data.orders.map(order => ({
      id: order.id,
      customerName: order.customer.name,
      totalAmount: order.totalAmount,
      status: orderStatusMachine.getStateLabel(order.status),
      createdAt: order.createdAt,
      updatedAt: order.updatedAt
    }));
    
    dataManager.exportToCSV(orders, `订单数据_${new Date().toLocaleDateString('zh-CN').replace(/\//g, '-')}.csv`);
  }
  
  // 初始化订单管理页面
  function initOrders() {
    // 绑定导出订单按钮事件
    const exportBtn = DOM.$('#orders-view .btn-secondary');
    if (exportBtn) {
      DOM.on(exportBtn, 'click', exportOrders);
    }
    
    // 监听视图切换事件
    DOM.on(document, 'viewChanged', (e) => {
      if (e.detail.viewId === 'orders') {
        currentPage = 1;
        renderOrders();
      }
    });
  }
  
  // 初始化
  initOrders();
});